<template>
  <el-dialog
    :title="formData.id ? '编辑商品' : '新增商品'"
    :visible="dialogVisible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    width="700px"
    center
  >
    <el-form
      ref="addEditForm"
      v-loading="isLoading > 0"
      :model="formData"
      :rules="rules"
      label-width="130px"
      class="add-edit-form"
    >
      <el-form-item label="所属分类" prop="cate_id">
        <el-select v-model="formData.cate_id" placeholder="选择分类">
          <el-option
            v-for="item in cateList"
            :key="item.id"
            :label="item.cate_name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="商品名称" prop="goods_name">
        <el-input v-model="formData.goods_name" />
      </el-form-item>
      <el-form-item label="商品描述" prop="goods_desc">
        <el-input v-model="formData.goods_desc" />
      </el-form-item>

      <el-form-item label="商品图片" prop="goods_image">
        <upload-img v-model="formData.goods_image" />
      </el-form-item>

      <el-form-item label="价格" prop="price">
        <el-input v-model="formData.price" />
      </el-form-item>

      <el-form-item label="规格" prop>
        <ul class="specs-box">
          <el-button type="primary" @click="addSpecs(formData.specs_list)">添加规格</el-button>
          <li v-for="(specs, specs_i) in formData.specs_list" :key="specs.id">
            <div class="specs-item">
              <el-input v-model="specs.title" class="input" placeholder="规格标题" />
              <!-- <label for="">排序:</label> -->
              <!-- <el-input v-model="specs.sort" class="input" placeholder="规格排序" /> -->
              <i class="icon el-icon-remove" @click="formData.specs_list.splice(specs_i, 1)" />
              <el-button
                type="primary"
                size="mini"
                @click="addOption(specs, specs.option_list)"
              >添加选项</el-button>
            </div>
            <ul class="option-box">
              <li
                v-for="(option, option_i) in specs.option_list"
                :key="option.id"
                class="option-item"
              >
                <el-input v-model="option.text" class="input" placeholder="名称" />
                <label for>附加价格:</label>
                <el-input v-model="option.price" class="input" placeholder="价格" />
                <!-- <label for="">排序:</label> -->
                <!-- <el-input v-model="option.sort" class="input" placeholder="排序" /> -->
                <i class="icon el-icon-remove" @click="specs.option_list.splice(option_i, 1)" />
              </li>
            </ul>
          </li>
        </ul>
      </el-form-item>

      <el-form-item label="组合商品" prop>
        <ul class="compose-box">
          <el-button type="primary" @click="addCompose(formData.compose_list)">添加组合商品</el-button>
          <li
            v-for="(compose, compose_i) in formData.compose_list"
            :key="compose.id"
            class="compose-item"
          >
            <el-select v-model="compose.id" class="select" placeholder="选择分类">
              <el-option
                v-for="item in cateList"
                :key="item.id"
                :label="item.cate_name"
                :value="item.id"
              />
            </el-select>
            <!-- <label for="">排序:</label> -->
            <!-- <el-input v-model="specs.sort" class="input" placeholder="排序" /> -->
            <i class="icon el-icon-remove" @click="formData.compose_list.splice(compose_i, 1)" />
          </li>
        </ul>
      </el-form-item>

      <el-form-item label="折后价" prop="discount_price">
        <el-input v-model="formData.discount_price" />
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input v-model="formData.sort" placeholder="请填入一个整数，数字越小越靠前" />
      </el-form-item>

      <el-form-item label="是否上线">
        <el-switch
          :value="formData.status === 1"
          active-color="#13ce66"
          inactive-color="#ff4949"
          @change="formData.status = formData.status === 1 ? -1 : 1"
        />
      </el-form-item>

      <el-form-item class="submit-box">
        <el-button type="primary" @click="submitForm()">提交</el-button>
        <el-button v-if="!formData.id" @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
const formData = {
  goods_name: '',
  goods_desc: '',
  cate_id: '',
  goods_image: '',
  price: '',
  discount_price: '',
  specs_list: [],
  compose_list: [],
  sort: 1,
  status: -1
}
import _ from 'lodash'
import UploadImg from '@/components/UploadImg'
// import { getCateGoodsList } from '@/api/cate'
import { addOneGoods, updateOneGoodsById } from '@/api/goods'
export default {
  name: 'GoodsAddEdit',
  components: {
    UploadImg
  },
  props: {
    cateList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      dialogVisible: false,
      isLoading: 0,
      formData: {},
      rules: {
        goods_name: [
          { required: true, message: '不能为空', trigger: ['change', 'blur'] }
        ],
        goods_image: [
          { required: true, message: '不能为空', trigger: ['change', 'blur'] }
        ],
        price: [
          { required: true, message: '不能为空', trigger: ['change', 'blur'] },
          { pattern: /^[1-9]\d*\.?\d*$/, message: '必须是一个数字', trigger: ['change', 'blur'] }
        ],
        discount_price: [
          { required: true, message: '不能为空', trigger: ['change', 'blur'] },
          { pattern: /^[1-9]\d*\.?\d*$/, message: '必须是一个数字', trigger: ['change', 'blur'] }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  created() {
  },
  mounted() {},
  methods: {
    addSpecs(arr) {
      arr.push({
        id: arr.length === 0 ? 1 : arr[arr.length - 1].id + 1,
        title: '',
        option_list: []
        // sort: 1,
        // status: 1
      })
    },
    addOption(specs, arr) {
      arr.push({
        id: arr.length === 0 ? Number.parseInt(specs.id + '01') : arr[arr.length - 1].id + 1,
        text: '',
        price: 0
        // sort: 1,
        // status: 1
      })
    },
    addCompose(arr) {
      // arr.push(null)
      arr.push({
        // id: arr.length === 0 ? 1 : arr[arr.length - 1].id + 1,
        id: null
        // sort: 1,
        // status: 1
      })
    },
    // async getCateList() {
    //   try {
    //     this.isLoading++
    //     this.cateList = await getCateGoodsList()
    //   } finally {
    //     this.isLoading--
    //   }
    // },
    handleClose() {
      this.dialogVisible = false
    },
    open(row) {
      this.dialogVisible = true
      this.formData = row ? _.cloneDeep(row) : _.cloneDeep(formData)
      this.$nextTick(() => {
        this.$refs.addEditForm.clearValidate()
      })
    },
    resetForm() {
      this.formData = { ...formData }
      this.$refs.addEditForm.resetFields()
    },
    toJson() {
      this.formData.specs_list_json = JSON.stringify(this.formData.specs_list)
      this.formData.compose_list_json = JSON.stringify(this.formData.compose_list)
    },
    submitForm() {
      if (this.isLoading > 0) return
      this.$refs.addEditForm.validate(async vaild => {
        if (!vaild) return
        try {
          this.isLoading++
          this.toJson()
          if (this.formData.id) {
            await updateOneGoodsById(this.formData)
          } else {
            await addOneGoods(this.formData)
          }
          this.$emit('refresh')
          this.handleClose()
        } finally {
          this.isLoading--
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.specs-item,
.option-item,
.compose-item {
  display: flex;
  align-items: center;
}

label {
  flex: none;
  width: 100px;
  text-align: right;
}

li {
  margin: 10px 0;
  list-style: none;
  &:last-child {
    margin-bottom: 0 !important;
  }
}
.icon {
  cursor: pointer;
  font-size: 30px;
  color: #409eff;
}
.specs-box {
  > li {
    border: 1px solid blue;
  }
}
.compose-box {
  .select {
    flex: none;
    width: 50%;
  }
}

.submit-box {
  display: flex;
  justify-content: flex-end;
}
</style>
